package com.ichir.projects.uiflow.internal.resolvers;

import com.ichir.projects.uiflow.definition.IFlowDefinition;
import com.ichir.projects.uiflow.definition.IFlowPart;
import com.ichir.projects.uiflow.definition.ITransition;
import com.ichir.projects.uiflow.definition.NoSuchTransitionException;
import com.ichir.projects.uiflow.internal.api.IFlowResolver;
import com.ichir.projects.uiflow.ui.api.IUiPart;

/**
 * Flow transition resolver: next, previous, ... flow states.
 * 
 * @author mahieddine
 */
public class TransitionResolver {

	private IFlowResolver flowResolver;
	
	private IFlowPart current;
	private IFlowPart previous;

	private IFlowDefinition flowDefinition;

	/**
	 * @return the flowDefinition
	 */
	public IFlowDefinition getFlowDefinition() {
		return flowDefinition;
	}

	/**
	 * @param flowDefinition the flowDefinition to set
	 */
	public void setFlowDefinition(IFlowDefinition flowDefinition) {
		this.flowDefinition = flowDefinition;
	}

	public TransitionResolver(IFlowPart initialFlowPart) {
		this.current = initialFlowPart;
		this.flowResolver = new FlowResolver();
	}

	public IFlowPart getCurrent() {
		return current;
	}
	
	public IFlowPart getNext(IUiPart uiPart, String transitionId) {
		IFlowPart tmp = flowResolver.resolveFlowPart(flowDefinition, uiPart);
		if (tmp != null) {
			current = tmp;
		}
		for (ITransition transition : current.getTransitions()) {
			if (transition.getId().equals(transitionId)) {
				synchronized (current) {
					previous = current;
					current = transition.getTo();
				}
				return current;
			}
		}
		throw new NoSuchTransitionException("transition with id "+transitionId+" not found");
		
	}

	public IFlowPart getPrevious() {
		return previous;
	}
}